<template>
  <inject-template :item="item" :pageId="pageId" :popId="popId">
    <template v-slot:common>
      <div class="wb-camera">
        <img v-if="cropImgUrl && isHtml2canvas" :src="cropImgUrl" class="crop-img" ref="cropImg">
        <img v-if="commonAttr.isCutImage" class="crop-frame" :src="commonAttr.cropFrameUrl" :style="cropFrameStyle">
        <canvas v-if="commonAttr.isCutImage" id="canvasImg"></canvas>
        <div class="drag-resize-con" v-if="isCroppa">
          <croppa
            v-show="!isHtml2canvas"
            :style="cameraStyles"
            ref="croppa_"
            v-model="croppa"
            :width="croppaWidth"
            :height="croppaHeight"
            prevent-white-space
            :canvas-color="commonAttr.canvasColor"
            :placeholder="placeholder"
            :placeholder-color="commonAttr.placeholderColor"
            :placeholder-font-size="commonAttr.placeholderFontSize"
            :show-remove-button="commonAttr.isShowRemoveButton"
            :remove-button-color="commonAttr.removeButtonColor"
            :remove-button-size="parseInt(commonAttr.delButtonSize)"
            :show-loading="commonAttr.isShowLoading"
            :loading-size="parseInt(commonAttr.loadingSize)"
            :loading-color="commonAttr.loadingColor"
            :zoom-speed="commonAttr.zoomSpeed"
            :quality="parseInt(commonAttr.quality)"
            :initial-image="commonAttr.initialImage"
            :file-size-limit="commonAttr.fSizeLimit"
            initial-size="cover"
            initial-position="center"
            :accept="accept"
            @file-size-exceed="onFileSizeExceed"
            @new-image-drawn="onComplete"
            @new-image="onChangeOrientation"
            @zoom="onZoom"
            @image-remove="onImageRemove"
            >
            <div class="spinner" v-if="croppa && croppa.loading"></div>
            <template v-slot:placeholder v-if="commonAttr.isPlaceholderImg">
              <img  class="img-placeholder" crossOrigin="anonymous" :src="commonAttr.placeholderUrl">
            </template>
          </croppa>
        </div>
        <img v-if="commonAttr.isCutImage" class="crop-line-left" :src="commonAttr.cropFrameLineUrl"  :style="cropFrameLeftStyle">
        <img v-if="commonAttr.isCutImage" class="crop-line-right" :src="commonAttr.cropFrameLineUrl"  :style="cropFrameRightStyle">

        <div v-show="isPoster && isDrawImg && isHavePoster" class="poster-con">
          <wb-moveable :item="item" :pageId="pageId" :popId="popId" ref="moveable"></wb-moveable>
        </div>
      </div>
    </template>
  </inject-template>
</template>

<script>
import InjectTemplate from '@/components/inject-template.vue'
import WbMoveable from '@/components/common/wb-moveable.vue'
import Croppa from '@/components/croppa/cropper.vue'
import { utils } from '@/components/utils/utils'
import { commonUtils } from '@/components/utils/common-utils'
import { EventBus } from '@/store/index'
import { MOBILE_WID_HEI } from '@/common/const-dif'
import { isWeibo, isJSON } from '@/plugins/utils'
import { reactive } from 'vue'
import { getPxOVwByValue } from '@/store/utils'

export default {
  name: 'WbCamera',
  mixins: [utils, commonUtils],
  components: {
    InjectTemplate,
    WbMoveable,
    Croppa
  },
  setup () {
    const state = reactive({
      cropImgUrl: "",
      isHtml2canvas: false,
      isDrawImg: false,
      isHavePoster: false,
      isCroppa: false,
    })
    const state_ = {
      croppa: {},
      cropFrameStyle: {
        top: 0,
        left: 0,
        width: 0,
        height: 0,
      },
      cropFrameLeftStyle: {
        top: 0,
        left: 0,
        width: 0,
        height: 0,
      },
      cropFrameRightStyle: {
        top: 0,
        left: 0,
        width: 0,
        height: 0,
      },
      rotateIndex: 1,
      interactionDataObj: {
        displayEventCompId: "",
        hiddenEventCompId: "",
      }
    }
    _.merge(state, state_)
    return state
  },
  created() {
    if(this.isH5Edit) return
    EventBus.$off("isStartHtml2canvas", this.onHiddenCroppa);
    EventBus.$on("isStartHtml2canvas", this.onHiddenCroppa);
    EventBus.$off("openCamera", this.onOpenCamera);
    EventBus.$on("openCamera", this.onOpenCamera);
    EventBus.$off("removeCamera", this.onRemoveCamera);
    EventBus.$on("removeCamera", this.onRemoveCamera);
    EventBus.$off("rotateCameraImg", this.onRotateCameraImg);
    EventBus.$on("rotateCameraImg", this.onRotateCameraImg);
    EventBus.$off("addImgToCanvas", this.onAddDragItemCanvas);
    EventBus.$on("addImgToCanvas", this.onAddDragItemCanvas);
    EventBus.$off("cameraDisplayMoveable", this.onCameraDisplayMoveable);
    EventBus.$on("cameraDisplayMoveable", this.onCameraDisplayMoveable);

    if(this.item.events.interactionData){
      const interactionDataStr = this.item.events.interactionData.comps[0].attrs.value;
      if(isJSON(interactionDataStr)){
        //{"displayEventCompId":"1bcf3e66-31bf-4ef1-9ba3-2e0edbc2aec6","hiddenEventCompId":"27dbf606-0a75-486a-a19b-9a7770bbd4db"}
        this.interactionDataObj = JSON.parse(interactionDataStr);
      }
    }
  },
  computed: {
    isPoster(){
      return this.commonAttr.isPoster
    },
    cameraStyles(){
      let styles_ = this.styles;
      _.merge(styles_, { backgroundColor: this.commonAttr.canvasColor});
      return styles_;
    },
    croppaWidth(){
      if(this.isH5Edit){
        return this.item.conAttr.width
      }else{
        let borderSize_ = this.commonAttr.borderSize_ ? this.commonAttr.borderSize_ : this.commonAttr.borderSize
        return parseInt((this.item.conAttr.width-borderSize_*this.commonAttr.quality)/MOBILE_WID_HEI.adaptiveScale);
      }
    },
    croppaHeight(){
      if(this.isH5Edit){
        return this.item.conAttr.height
      }else{
        let borderSize_ = this.commonAttr.borderSize_ ? this.commonAttr.borderSize_ : this.commonAttr.borderSize
        return parseInt((this.item.conAttr.height-borderSize_*this.commonAttr.quality)/MOBILE_WID_HEI.adaptiveScale);
      }
    },
    placeholder() {
      return this.$refs.croppa_ && this.$refs.croppa_.loading ? '' : this.commonAttr.placeholder
    },
    accept(){
      if(isWeibo()){
        return "image/*"
      }else{
        return ""
      }
    },
  },
  mounted(){
    if(!this.isH5Edit){
      this.initCroppa();
    }
    this.computeFrameStyle();
  },
  methods: {
    onAddDragItemCanvas(){
      if(this.isPoster && this.isDrawImg){
        //
      }else{
        this.showAlert("亲，先从相册中选择图片哦！")
      }
    },
    onRemoveCamera(){
      if(this.$refs.croppa_){
        this.$refs.croppa_.remove();
      }
      if(this.$refs.moveable) {
        this.$refs.moveable.clearDragIcon();
      }
    },
    onCameraDisplayMoveable({ isDisplay }){
      this.isHavePoster = isDisplay;
      this.item.commonAttr.isAddPoster = isDisplay;
    },
    onOpenCamera(){
      this.$refs.croppa_.chooseFile();
    },
    onRotateCameraImg(){
      this.$refs.croppa_.rotate(this.rotateIndex);
      this.rotateIndex++;
    },
    onHiddenCroppa({ isStart, compId }){
      this.onMove();
      if(compId === this.item.id){
        this.isHtml2canvas = isStart;
      }
    },
    computeFrameStyle(){
      let cropFrame = new Image();
      cropFrame.src = this.commonAttr.cropFrameUrl;
      cropFrame.onload = (e) => {
        let img = e.target;
        this.cropFrameStyle.width = getPxOVwByValue(img.width)
        this.cropFrameStyle.height = getPxOVwByValue(img.height)
        this.cropFrameStyle.top = getPxOVwByValue(-(img.height - this.item.conAttr.height - 8)/2)
        this.cropFrameStyle.left = getPxOVwByValue((this.item.conAttr.width - img.width)/2)

        let cropFrameLine = new Image();
        cropFrameLine.src = this.commonAttr.cropFrameLineUrl;
        cropFrameLine.onload = (e) => {
          let imgLine = e.target;
          this.cropFrameLeftStyle.width = getPxOVwByValue(imgLine.width)
          this.cropFrameLeftStyle.height = getPxOVwByValue(imgLine.height)
          this.cropFrameLeftStyle.left = getPxOVwByValue((this.item.conAttr.width - img.width)/2)
          this.cropFrameRightStyle.width = getPxOVwByValue(imgLine.width)
          this.cropFrameRightStyle.height = getPxOVwByValue(imgLine.height)
          this.cropFrameRightStyle.left = getPxOVwByValue((this.item.conAttr.width - img.width)/2 + img.width)
        }
      }
    },
    onMove(){
      window.clearTimeout(this.timeoutCb);
      if(this.commonAttr.isCutImage){
        this.timeoutCb = setTimeout(() => {
          let CROPPA_WID = this.item.conAttr.width;
          let CROPPA_HEI = this.item.conAttr.height;
          let canvas = document.getElementById("canvasImg");
          let ctx = canvas.getContext("2d");
          let img = this.$refs.cropImg;
          let scale = this.commonAttr.scale ? this.commonAttr.scale: 9/20
          let adaptiveScale = MOBILE_WID_HEI.adaptiveScale/MOBILE_WID_HEI.designScale
          let cropWid = parseInt(scale * CROPPA_HEI/adaptiveScale);
          let offsetX = parseInt((CROPPA_WID/adaptiveScale - cropWid)/2)
          let cropHei = CROPPA_HEI/adaptiveScale;
          canvas.width = cropWid;
          canvas.height = cropHei;
          canvas.style.width = getPxOVwByValue(cropWid);
          canvas.style.height = getPxOVwByValue(cropHei);
          ctx.drawImage(img, offsetX, 0, cropWid, cropHei, 0, 0, cropWid, cropHei);
          let canResultBase64 = canvas.toDataURL('image/' + this.commonAttr.saveImgType, Number(this.commonAttr.saveImgQuality));
          this.commonAttr.cropImgUrl = this.cropImgUrl = canResultBase64;
        }, 100)
      }else{
        if(this.commonAttr.isPostInitialImg){
          this.commonAttr.cropImgUrl = this.cropImgUrl = this.$refs.croppa_.originalImage.src
        }else{
          this.commonAttr.cropImgUrl = this.cropImgUrl = this.$refs.croppa_.generateDataUrl(this.commonAttr.saveImgType, this.commonAttr.saveImgQuality);
        }
      }
    },
    onOpenPhotoAlbum(){
      this.openPhotoCb = window.setInterval(() => {
        if(this.$refs.croppa_ && this.$refs.croppa_.chooseFile){
          window.clearInterval(this.openPhotoCb);
          this.$refs.croppa_.chooseFile();
          if(this.interactionData) this.interactionData.isOpenCamera = true;
        }
      }, this.siteInfo.reloadTime)
    },
    onComplete(){
      if(this.isH5Edit){
        return
      }
      if(this.commonAttr.isPostInitialImg){
        this.commonAttr.cropImgUrl = this.cropImgUrl = this.$refs.croppa_.originalImage.src
      }else{
        this.commonAttr.cropImgUrl = this.cropImgUrl = this.$refs.croppa_.generateDataUrl('image/jpeg', 0.8);
      }
      this.isDrawImg = true;

      if(this.interactionDataObj){
        EventBus.$emit("itemClick", {id: this.interactionDataObj.displayEventCompId, index: 0});
      }
      // this.dragLists.push({ url: this.cropImgUrl, width: this.item.conAttr.width/MOBILE_WID_HEI.adaptiveScale, height: this.item.conAttr.height/MOBILE_WID_HEI.adaptiveScale});
      // this.onMove();
    },
    onChangeOrientation(){
      const metadata = {
        orientation: 1
      };
      this.$refs.croppa_.applyMetadata(metadata);
    },
    onImageRemove(){
      this.isDrawImg = false;
      // 删除图片数据
      this.cropImgUrl = null
      this.$store.commit('updateComponentAttr', { id: this.item.id, commonAttr:{cropImgUrl: null} })
      if(this.interactionDataObj){
        EventBus.$emit("itemClick", {id: this.interactionDataObj.hiddenEventCompId, index: 0});
      }
    },
    initCroppa(){
      // if(Croppa){
        // this.app.use(Croppa);
        this.isCroppa = true;

        if(!this.isH5Edit && this.commonAttr.isAutoOpen && this.interactionData && !this.interactionData.isOpenCamera){
          this.onOpenPhotoAlbum()
        }
      // }
    },
    onFileSizeExceed(){
      this.showAlert("选择的图片太大了")
    },
    onZoom(){
      if(this.$refs.croppa_.scaleRatio > 3){
        this.$refs.croppa_.scaleRatio = 3
      }
    },
  },
  beforeUnmount(){
    if(this.isH5Edit) return
    EventBus.$off("isStartHtml2canvas", this.onHiddenCroppa);
    EventBus.$off("openCamera", this.onOpenCamera);
    EventBus.$off("cameraDisplayMoveable", this.onCameraDisplayMoveable);

    if(this.interactionData) this.interactionData.isOpenCamera = false;
  }
};
</script>

<style lang="scss" scoped>
.poster-con{
  width: inherit;
  height: inherit;
  img{
    width: inherit;
    height: inherit;
  }
}
.wb-camera, .img-placeholder{
  width: inherit;
  height: inherit;
  position: relative;
}
.crop-frame{
  position: absolute;
}
 .crop-img{
  position: absolute;
  width: inherit;
  height: inherit;
 }
.crop-line-left{
  position: absolute;
  top: 0;
}
.crop-line-right{
  position: absolute;
  top: 0;
}
.drag-resize-con{
  position: absolute;
  top: 0;
  left: 0;
  height: inherit;
  width: inherit;

  img{
    height: 100%;
    object-fit: cover;
    text-align: center;
  }
}


.sk-fading-circle {
  position: absolute; }
  .sk-fading-circle .sk-circle {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0; }
  .sk-fading-circle .sk-circle .sk-circle-indicator {
    display: block;
    margin: 0 auto;
    width: 15%;
    height: 15%;
    border-radius: 100%;
    -webkit-animation: sk-circleFadeDelay 1s infinite ease-in-out both;
            animation: sk-circleFadeDelay 1s infinite ease-in-out both; }
  .sk-fading-circle .sk-circle2 {
    -webkit-transform: rotate(30deg);
            transform: rotate(30deg); }
  .sk-fading-circle .sk-circle3 {
    -webkit-transform: rotate(60deg);
            transform: rotate(60deg); }
  .sk-fading-circle .sk-circle4 {
    -webkit-transform: rotate(90deg);
            transform: rotate(90deg); }
  .sk-fading-circle .sk-circle5 {
    -webkit-transform: rotate(120deg);
            transform: rotate(120deg); }
  .sk-fading-circle .sk-circle6 {
    -webkit-transform: rotate(150deg);
            transform: rotate(150deg); }
  .sk-fading-circle .sk-circle7 {
    -webkit-transform: rotate(180deg);
            transform: rotate(180deg); }
  .sk-fading-circle .sk-circle8 {
    -webkit-transform: rotate(210deg);
            transform: rotate(210deg); }
  .sk-fading-circle .sk-circle9 {
    -webkit-transform: rotate(240deg);
            transform: rotate(240deg); }
  .sk-fading-circle .sk-circle10 {
    -webkit-transform: rotate(270deg);
            transform: rotate(270deg); }
  .sk-fading-circle .sk-circle11 {
    -webkit-transform: rotate(300deg);
            transform: rotate(300deg); }
  .sk-fading-circle .sk-circle12 {
    -webkit-transform: rotate(330deg);
            transform: rotate(330deg); }
  .sk-fading-circle .sk-circle2 .sk-circle-indicator {
    -webkit-animation-delay: -0.91667s;
            animation-delay: -0.91667s; }
  .sk-fading-circle .sk-circle3 .sk-circle-indicator {
    -webkit-animation-delay: -0.83333s;
            animation-delay: -0.83333s; }
  .sk-fading-circle .sk-circle4 .sk-circle-indicator {
    -webkit-animation-delay: -0.75s;
            animation-delay: -0.75s; }
  .sk-fading-circle .sk-circle5 .sk-circle-indicator {
    -webkit-animation-delay: -0.66667s;
            animation-delay: -0.66667s; }
  .sk-fading-circle .sk-circle6 .sk-circle-indicator {
    -webkit-animation-delay: -0.58333s;
            animation-delay: -0.58333s; }
  .sk-fading-circle .sk-circle7 .sk-circle-indicator {
    -webkit-animation-delay: -0.5s;
            animation-delay: -0.5s; }
  .sk-fading-circle .sk-circle8 .sk-circle-indicator {
    -webkit-animation-delay: -0.41667s;
            animation-delay: -0.41667s; }
  .sk-fading-circle .sk-circle9 .sk-circle-indicator {
    -webkit-animation-delay: -0.33333s;
            animation-delay: -0.33333s; }
  .sk-fading-circle .sk-circle10 .sk-circle-indicator {
    -webkit-animation-delay: -0.25s;
            animation-delay: -0.25s; }
  .sk-fading-circle .sk-circle11 .sk-circle-indicator {
    -webkit-animation-delay: -0.16667s;
            animation-delay: -0.16667s; }
  .sk-fading-circle .sk-circle12 .sk-circle-indicator {
    -webkit-animation-delay: -0.08333s;
            animation-delay: -0.08333s; }

@-webkit-keyframes sk-circleFadeDelay {
  0%,
  39%,
  100% {
    opacity: 0; }
  40% {
    opacity: 1; } }

@keyframes sk-circleFadeDelay {
  0%,
  39%,
  100% {
    opacity: 0; }
  40% {
    opacity: 1; } }

.croppa-container {
  display: inline-block;
  cursor: pointer;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
  position: relative;
  font-size: 0;
  -ms-flex-item-align: start;
      align-self: flex-start;
  background-color: transparent;
  height: inherit;
}
.croppa-container canvas {
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
}
.croppa-container:hover {
  opacity: 0.7;
}
.croppa-container.croppa--dropzone {
  -webkit-box-shadow: inset 0 0 10px #333;
          box-shadow: inset 0 0 10px #333;
}
.croppa-container.croppa--dropzone canvas {
  opacity: 0.5;
}
.croppa-container.croppa--disabled-cc {
  cursor: default;
}
.croppa-container.croppa--disabled-cc:hover {
  opacity: 1;
}
.croppa-container.croppa--has-target {
  cursor: move;
}
.croppa-container.croppa--has-target:hover {
  opacity: 1;
}
.croppa-container.croppa--has-target.croppa--disabled-mz {
  cursor: default;
}
.croppa-container.croppa--disabled {
  cursor: not-allowed;
}
.croppa-container.croppa--disabled:hover {
  opacity: 1;
}
.croppa-container.croppa--passive {
  cursor: default;
}
.croppa-container.croppa--passive:hover {
  opacity: 1;
}
.croppa-container svg.icon-remove {
  position: absolute;
  background: #fff;
  border-radius: 50%;
  -webkit-filter: drop-shadow(-2px 2px 2px rgba(0,0,0,0.7));
          filter: drop-shadow(-2px 2px 2px rgba(0,0,0,0.7));
  z-index: 10;
  cursor: pointer;
  border: 2px solid #fff;
}


</style>
